/*
 *  linux/arch/arm/mm/alignment.c
 *
 *  Copyright (C) 1995  Linus Torvalds
 *  Modifications for ARM processor (c) 1995-2001 Russell King
 *  Thumb alignment fault fixups (c) 2004 MontaVista Software, Inc.
 *  - Adapted from gdb/sim/arm/thumbemu.c -- Thumb instruction emulation.
 *    Copyright (C) 1996, Cygnus Software Technologies Ltd.
 *
 *  Only maintain armv8 aligment fault fixups, remove the other
 *  architecture and remove thumb/thumb-2 instrutions.
 *  Hardware only support unalignment access for some instrutions,
 *  need to add ldm/stm/ldrd/strd word/double instructions.
 *  Otherwise,we add a new feature for normal uncacheable
 *  attribute-memory unalignment access.
 *		Copyright (c) 2018-2019, Huawei Technologies Co., Ltd.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 */
#include <linux/moduleparam.h>
#include <linux/compiler.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/uaccess.h>
#include <asm/opcodes.h>
#include <asm/unaligned.h>
#include <asm/system_misc.h>
#include "fault.h"

/*
 * 32-bit misaligned trap handler (c) 1998 San Mehat (CCC) -July 1998
 * /proc/sys/debug/alignment, modified and integrated into
 * Linux 2.1 by Russell King
 *
 * Speed optimisations and better fault handling by Russell King.
 *
 * *** NOTE ***
 * This code is not portable to processors with late data abort handling.
 */
#define CODING_BITS(i)	(i & 0x0e000000)
#define COND_BITS(i)	(i & 0xf0000000)

#define LDST_P_BIT(i)	(i & (1 << 24))		/* Preindex		*/
#define LDST_U_BIT(i)	(i & (1 << 23))		/* Add offset		*/
#define LDST_W_BIT(i)	(i & (1 << 21))		/* Writeback		*/
#define LDST_L_BIT(i)	(i & (1 << 20))		/* Load			*/

#define LDST_P_EQ_U(i)	((((i) ^ ((i) >> 1)) & (1 << 23)) == 0)

#define LDSTHD_I_BIT(i)	(i & (1 << 22))		/* double/half-word immed */
#define LDM_S_BIT(i)	(i & (1 << 22))		/* write CPSR from SPSR	*/

#define RN_BITS(i)	((i >> 16) & 15)	/* Rn			*/
#define RD_BITS(i)	((i >> 12) & 15)	/* Rd			*/
#define RM_BITS(i)	(i & 15)		/* Rm			*/

#define REGMASK_BITS(i)	(i & 0xffff)
#define OFFSET_BITS(i)	(i & 0x0fff)

#define IS_SHIFT(i)	(i & 0x0ff0)
#define SHIFT_BITS(i)	((i >> 7) & 0x1f)
#define SHIFT_TYPE(i)	(i & 0x60)
#define SHIFT_LSL	0x00
#define SHIFT_LSR	0x20
#define SHIFT_ASR	0x40
#define SHIFT_RORRRX	0x60

#define UM_FIXUP	0x00000000
#define UM_WARN		0x00000001

static unsigned long ai_user;
static unsigned long ai_skipped;
static unsigned long ai_half;
static unsigned long ai_word;
static unsigned long ai_dword;
static unsigned long ai_multi;
static int ai_usermode = UM_FIXUP;

#ifdef CONFIG_PROC_FS
static const char * const usermode_action[] = {
	"fixup",
	"fixup+warn"
};

static int alignment_proc_show(struct seq_file *m, void *v)
{
	seq_printf(m, "User:\t\t%lu\n", ai_user);
	seq_printf(m, "Skipped:\t%lu\n", ai_skipped);
	seq_printf(m, "Half:\t\t%lu\n", ai_half);
	seq_printf(m, "Word:\t\t%lu\n", ai_word);
	seq_printf(m, "DWord:\t\t%lu\n", ai_dword);
	seq_printf(m, "Multi:\t\t%lu\n", ai_multi);
	seq_printf(m, "Handle Mode :\t(%s) %i\n",
			usermode_action[ai_usermode], ai_usermode);

	return 0;
}

static int alignment_proc_open(struct inode *inode, struct file *file)
{
	return single_open(file, alignment_proc_show, NULL);
}

static ssize_t alignment_proc_write(struct file *file, const char __user *buffer,
				    size_t count, loff_t *pos)
{
	char mode;

	if (count > 0) {
		if (get_user(mode, buffer))
			return -EFAULT;
		if ('1' == mode)
			ai_usermode |= UM_WARN;
		else
			ai_usermode = UM_FIXUP;
	}
	return count;
}

static const struct proc_ops alignment_proc_ops = {
	.proc_open		= alignment_proc_open,
	.proc_read		= seq_read,
	.proc_lseek		= seq_lseek,
	.proc_release	= single_release,
	.proc_write		= alignment_proc_write,
};
#endif /* CONFIG_PROC_FS */

union offset_union {
	unsigned long un;
	  signed long sn;
};

#define TYPE_ERROR	0
#define TYPE_FAULT	1
#define TYPE_LDST	2
#define TYPE_DONE	3

#ifdef __BIG_ENDIAN
#define BE		1
#define FIRST_BYTE_16	"ror	%w1, %w1, #8\n"
#define FIRST_BYTE_32	"ror	%w1, %w1, #24\n"
#define NEXT_BYTE	"ror %w1, %w1, #24\n"
#else
#define BE		0
#define FIRST_BYTE_16
#define FIRST_BYTE_32
#define NEXT_BYTE	"lsr %w1, %w1, #8\n"
#endif

#define __get8_unaligned_check(ins, val, addr, err)	\
	do {								\
		__asm__ volatile(					\
		"1:	"ins"	%w1, [%2]\n"		\
		"	add	%2, %2, #1\n"		\
		"2:\n"						\
		"	.section .fixup,\"ax\"\n"	\
		"	.align	2\n"				\
		"3:	mov	%w0, #1\n"			\
		"	b	2b\n"				\
		"	.previous\n"				\
		_ASM_EXTABLE(1b, 3b)            \
		: "=r" (err), "=&r" (val), "=r" (addr)		\
		: "0" (err), "2" (addr)); \
	} while (0)

#define __get16_unaligned_check(ins, val, addr)			\
	do {							\
		unsigned int err = 0, v;		\
		unsigned long a = addr;			\
		__get8_unaligned_check(ins, v, a, err);		\
		val =  v << ((BE) ? 8 : 0);			\
		__get8_unaligned_check(ins, v, a, err);		\
		val |= v << ((BE) ? 0 : 8);			\
		if (err)					\
			goto fault;				\
	} while (0)

#define get16t_unaligned_check(val, addr) \
	__get16_unaligned_check("ldtrb", val, addr)

#define __get32_unaligned_check(ins, val, addr)		\
	do {							\
		unsigned int err = 0, v = 0;	\
		unsigned long a = addr;		\
		__get8_unaligned_check(ins, v, a, err);		\
		val =  v << ((BE) ? 24 :  0);			\
		__get8_unaligned_check(ins, v, a, err);		\
		val |= v << ((BE) ? 16 :  8);			\
		__get8_unaligned_check(ins, v, a, err);		\
		val |= v << ((BE) ?  8 : 16);			\
		__get8_unaligned_check(ins, v, a, err);		\
		val |= v << ((BE) ?  0 : 24);			\
		if (err)					\
			goto fault;				\
	} while (0)

#define get32t_unaligned_check(val, addr) \
	__get32_unaligned_check("ldtrb", val, addr)

#define __put16_unaligned_check(ins, val, addr)			\
	do {							\
		unsigned int err = 0, v = val;	\
		unsigned long a = addr;		\
		__asm__ volatile(FIRST_BYTE_16				\
		"1:	"ins"	%w1, [%2]\n"		\
		"	add	%2, %2, #1\n"		\
			NEXT_BYTE		\
		"2:	"ins"	%w1, [%2]\n"			\
		"3:\n"						\
		"	.section .fixup,\"ax\"\n"	\
		"	.align	2\n"				\
		"4:	mov	%w0, #1\n"			\
		"	b	3b\n"				\
		"	.previous\n"				\
		_ASM_EXTABLE(1b, 4b)                \
		_ASM_EXTABLE(2b, 4b)                \
		: "=r" (err), "=&r" (v), "=&r" (a)		\
		: "0" (err), "1" (v), "2" (a));			\
		if (err)					\
			goto fault;				\
	} while (0)

#define put16t_unaligned_check(val, addr) \
	__put16_unaligned_check("sttrb", val, addr)

#define __put32_unaligned_check(ins, val, addr)			\
	do {							\
		unsigned int err = 0, v = val;	\
		unsigned long a = addr;		\
		__asm__ volatile(FIRST_BYTE_32		\
		"1:	"ins"	%w1, [%2]\n"		\
		"	add	%2, %2, #1\n"		\
			NEXT_BYTE		\
		"2: "ins"   %w1, [%2]\n"        \
		"   add %2, %2 ,#1\n"       \
			NEXT_BYTE           \
		"3:	"ins"	%w1, [%2]\n"		\
		"	add	%2, %2, #1\n"		\
			NEXT_BYTE		\
		"4:	"ins"	%w1, [%2]\n"			\
		"5:\n"						\
		"	.section .fixup,\"ax\"\n"	\
		"	.align	2\n"				\
		"6:	mov	%w0, #1\n"			\
		"	b	5b\n"				\
		"	.previous\n"				\
		_ASM_EXTABLE(1b, 6b)            \
		_ASM_EXTABLE(2b, 6b)            \
		_ASM_EXTABLE(3b, 6b)            \
		_ASM_EXTABLE(4b, 6b)            \
		: "=r" (err), "=&r" (v), "=&r" (a)		\
		: "0" (err), "1" (v), "2" (a));			\
		if (err)					\
			goto fault;				\
	} while (0)

#define put32t_unaligned_check(val, addr) \
	__put32_unaligned_check("sttrb", val, addr)

static void
do_alignment_finish_ldst(unsigned long addr, u32 instr, struct pt_regs *regs, union offset_union offset)
{
	if (!LDST_U_BIT(instr))
		offset.un = -offset.un;

	if (!LDST_P_BIT(instr))
		addr += offset.un;

	if (!LDST_P_BIT(instr) || LDST_W_BIT(instr))
		regs->regs[RN_BITS(instr)] = addr;
}

static int
do_alignment_ldrhstrh(unsigned long addr, u32 instr, struct pt_regs *regs)
{
	unsigned int rd = RD_BITS(instr);

	ai_half += 1;

	if (a32_user_mode(regs)) {
		if (LDST_L_BIT(instr)) {
			unsigned long val;

			get16t_unaligned_check(val, addr);

			/* signed half-word? */
			if (instr & 0x40)
				val = (signed long)((signed short) val);

			regs->regs[rd] = val;
		} else
			put16t_unaligned_check(regs->regs[rd], addr);

		return TYPE_LDST;
	}

 fault:
	return TYPE_FAULT;
}

static int
do_alignment_ldrdstrd(unsigned long addr, u32 instr, struct pt_regs *regs)
{
	const unsigned int rd = RD_BITS(instr);
	unsigned int rd2;
	int load;

	if (((rd & 1) == 1) || (rd == 14)) {
		goto bad;
	} else {
		load = ((instr & 0xf0) == 0xd0);
		rd2 = rd + 1;
	}

	ai_dword += 1;
	if (a32_user_mode(regs)) {
		if (load) {
			unsigned long val;

			get32t_unaligned_check(val, addr);
			regs->regs[rd] = val;
			get32t_unaligned_check(val, addr + 4);
			regs->regs[rd2] = val;
		} else {
			put32t_unaligned_check(regs->regs[rd], addr);
			put32t_unaligned_check(regs->regs[rd2], addr + 4);
		}
	}

	return TYPE_LDST;
 bad:
	return TYPE_ERROR;
 fault:
	return TYPE_FAULT;
}

static int
do_alignment_ldrstr(unsigned long addr, u32 instr, struct pt_regs *regs)
{
	unsigned int rd = RD_BITS(instr);

	ai_word += 1;

	if ((!LDST_P_BIT(instr) && LDST_W_BIT(instr)) || a32_user_mode(regs)) {
		if (LDST_L_BIT(instr)) {
			unsigned int val;

			get32t_unaligned_check(val, addr);
			regs->regs[rd] = val;
		} else
			put32t_unaligned_check(regs->regs[rd], addr);

		return TYPE_LDST;
	}

 fault:
	return TYPE_FAULT;
}

static int
do_alignment_ldmstm(unsigned long addr, u32 instr, struct pt_regs *regs)
{
	unsigned int rd, rn, correction, nr_regs, regbits;
	/*
	 * if eaddr/newaddr use long type, SIGBUS will be happened,
	 * when stmda/ldmda/stmdb/ldmdb/ldmfa/stmfd/ldmea/stmed is
	 * unalign-accessed in arm64.
	 *
	 * MUST use int type
	 */
	unsigned int eaddr, newaddr;

	if (LDM_S_BIT(instr))
		goto bad;

	ai_multi += 1;
	correction = 4; /* processor implementation defined */
	regs->pc += correction;

	/* count the number of registers in the mask to be transferred */
	nr_regs = hweight16(REGMASK_BITS(instr)) * 4;

	rn = RN_BITS(instr);
	newaddr = eaddr = regs->regs[rn];

	if (!LDST_U_BIT(instr))
		nr_regs = -nr_regs;
	newaddr += nr_regs;
	if (!LDST_U_BIT(instr))
		eaddr = newaddr;

	if (LDST_P_EQ_U(instr))	/* U = P */
		eaddr += 4;

	if (a32_user_mode(regs)) {
		for (regbits = REGMASK_BITS(instr), rd = 0; regbits;
		     regbits >>= 1, rd += 1)
			if (regbits & 1) {
				if (LDST_L_BIT(instr)) {
					unsigned int val = 0;

					get32t_unaligned_check(val, eaddr);
					regs->regs[rd] = val;
				} else
					put32t_unaligned_check(regs->regs[rd], eaddr);
				eaddr += 4;
			}
	}

	if (LDST_W_BIT(instr))
		regs->regs[rn] = newaddr;
	if (!LDST_L_BIT(instr) || !(REGMASK_BITS(instr) & (1 << 15)))
		regs->pc -= correction;

	return TYPE_DONE;

fault:
	regs->pc -= correction;
	return TYPE_FAULT;

bad:
	pr_err("Alignment trap: not handling ldm with s-bit set\n");
	return TYPE_ERROR;
}

int do_alignment(unsigned long addr, unsigned int fsr, struct pt_regs *regs)
{
	union offset_union offset;
	unsigned long instrptr;
	int (*handler)(unsigned long addr, u32 instr, struct pt_regs *regs) = NULL;
	unsigned int type;
	u32 instr = 0;
	unsigned int fault;
	const unsigned int isize = 4;

	/*
	 * back up regs and regs->pc
	 * the regs are for the modify of regs
	 * and the pc is for checking if regs->pc haas been
	 * changed by other process
	 */
	struct pt_regs backup_regs;
	unsigned long backup_pc;
	unsigned long flags;

	bool loads_to_the_pc = false;
	unsigned int regs_size = sizeof(struct pt_regs);

	local_irq_save(flags);
	backup_pc = regs->pc;
	memcpy(&backup_regs, regs, (size_t)regs_size);
	local_irq_restore(flags);

	instrptr = instruction_pointer(&backup_regs);
	if (a32_user_mode(&backup_regs))
		fault = __get_user(instr, (u32 *)(uintptr_t)instrptr);
	else
		fault = get_kernel_nofault(instr, (u32 *)(uintptr_t)instrptr);

	instr = __mem_to_opcode_arm(instr);

	if (instr == 0xe320f000) { /* check whether the instr is NOP */
		pr_err("The PC was changed to the fast user irq entry of SRE.\n");
		return 0;
	}

	if (fault) {
		type = TYPE_FAULT;
		goto bad_or_fault;
	}

	/*
	 * check if the user space process that traps into this file
	 * is 32-bits or 64-bits, not handling 64-bits misaligned access fault.
	 */
	if (a32_user_mode(&backup_regs)) {
		/* 32 bits user space process. */
		ai_user += 1;

		if (ai_usermode) {
			pr_err("32-bits Alignment trap: %s %d PC=0x%08lx Instr=0x%0*x Address=0x%08lx FSR 0x%03x\n",
					current->comm, task_pid_nr(current), instrptr, isize << 1, instr, addr, fsr);
			show_pte(addr);
		}
		goto fixup;
	} else {
		if (ai_usermode) {
			/* 64 bits user space process. address */
			pr_err("64-bits unaligned memory access: %s %d PC=0x%08lx Instr=0x%0*x Address=0x%08lx FSR 0x%03x\n",
					current->comm, task_pid_nr(current), instrptr, isize << 1, instr, addr, fsr);
			show_pte(addr);
			dump_stack();
		}
		/* kill the 64-bits process */
		type = TYPE_FAULT;
		goto bad_or_fault;
	}

 fixup:

	backup_regs.pc += isize;

	switch (CODING_BITS(instr)) {
	case 0x00000000:	/* 3.13.4 load/store instruction extensions */
		/* if Rd is 0xf in ldrd/strd instr, pc = Rd */
		loads_to_the_pc = (RD_BITS(instr) == 0xf) ? true : false;
		if (LDSTHD_I_BIT(instr))
			offset.un = (instr & 0xf00) >> 4 | (instr & 15);
		else
			offset.un = backup_regs.regs[RM_BITS(instr)];

		if ((instr & 0x000000f0) == 0x000000b0 || /* LDRH, STRH */
		    (instr & 0x001000f0) == 0x001000f0)   /* LDRSH */
			handler = do_alignment_ldrhstrh;
		else if ((instr & 0x001000f0) == 0x000000d0 || /* LDRD */
			 (instr & 0x001000f0) == 0x000000f0)   /* STRD */
			handler = do_alignment_ldrdstrd;
		else	/* other load or store instructions */
			goto bad;
		break;

	case 0x04000000:	/* ldr or str immediate */
		/* if Rd is 0xf in ldr/str instr, pc = Rd */
		loads_to_the_pc = (RD_BITS(instr) == 0xf) ? true : false;
		if (COND_BITS(instr) == 0xf0000000) /* NEON VLDn, VSTn */
			goto bad;
		offset.un = OFFSET_BITS(instr);
		handler = do_alignment_ldrstr;
		break;

	case 0x06000000:	/* ldr or str register */
		/* if Rd is 0xf in ldr/str instr, pc = Rd */
		loads_to_the_pc = (RD_BITS(instr) == 0xf) ? true : false;
		offset.un = backup_regs.regs[RM_BITS(instr)];

		if (IS_SHIFT(instr)) {
			unsigned int shiftval = SHIFT_BITS(instr);

			switch (SHIFT_TYPE(instr)) {
			case SHIFT_LSL:
				offset.un <<= shiftval;
				break;

			case SHIFT_LSR:
				offset.un >>= shiftval;
				break;

			case SHIFT_ASR:
				offset.sn >>= shiftval;
				break;

			case SHIFT_RORRRX:
				if (shiftval == 0) {
					offset.un >>= 1;
					if (backup_regs.pstate & PSR_C_BIT)
						offset.un |= 1 << 31;
				} else
					offset.un = offset.un >> shiftval |
							  offset.un << (32 - shiftval);
				break;
			}
		}
		handler = do_alignment_ldrstr;
		break;

	case 0x08000000:	/* ldm or stm  instruction */
		loads_to_the_pc = LDST_L_BIT(instr) && ((REGMASK_BITS(instr) & (1 << 15)));
		handler = do_alignment_ldmstm;
		break;

	default:
		goto bad;
	}

	if (!handler)
		goto bad;
	type = handler(addr, instr, &backup_regs);

	if (type == TYPE_ERROR || type == TYPE_FAULT) {
		backup_regs.pc -= isize;
		goto bad_or_fault;
	}

	if (type == TYPE_LDST)
		do_alignment_finish_ldst(addr, instr, &backup_regs, offset);

	/*
	 * 1,check if regs->pc has been modified during the unalignment handling
	 * 2,if load a new value to the PC
	 *  the new is loaded to regs[15] which is compat_sp_hyp on ARM64
	 *  and the PC is independent on ARM64
	 *  so have to move regs.regs[15] to regs.pc
	 */

	local_irq_save(flags);
	if (regs->pc != backup_pc) {
		local_irq_restore(flags);
		pr_err("The PC of user space has been changed by others,so we don`t handle this !\n");
		return 0;
	} else if (false == loads_to_the_pc) {
		memcpy(regs, &backup_regs, (size_t)regs_size);
	} else {
		backup_regs.pc = backup_regs.regs[15];
		backup_regs.regs[15] = regs->regs[15];
		memcpy(regs, &backup_regs, (size_t)regs_size);
	}
	local_irq_restore(flags);

	return 0;

 bad_or_fault:
	if (type == TYPE_ERROR)
		goto bad;
	/*
	 * We got a fault - fix it up, or die.
	 */
	do_bad_area(addr, fsr, &backup_regs);
	local_irq_save(flags);
	if (regs->pc != backup_pc) {
		local_irq_restore(flags);
		pr_err("The PC of user space has been changed by others,so we don`t handle this !\n");
		return 0;
	} else {
		memcpy(regs, &backup_regs, (size_t)regs_size);
	}
	local_irq_restore(flags);

	return 0;

 bad:
	/*
	 * Oops, we didn't handle the instruction.
	 */
	if (ai_usermode) {
		pr_err("Alignment trap: not handling instruction %0*x at [<%08lx>]\n",
				isize << 1, instr, instrptr);
		show_pte(addr);
	}

	ai_skipped += 1;
	return 1;
}

/*
 * This needs to be done after sysctl_init, otherwise sys/ will be
 * overwritten.  Actually, this shouldn't be in sys/ at all since
 * it isn't a sysctl, and it doesn't contain sysctl information.
 * We now locate it in /proc/cpu/alignment instead.
 */
static int __init alignment_init(void)
{
#ifdef CONFIG_PROC_FS
	struct proc_dir_entry *proc_dir = NULL;
	struct proc_dir_entry *res = NULL;

	proc_dir = proc_mkdir("cpu", NULL);
	if (!proc_dir) {
		res = proc_create("alignment", S_IWUSR | S_IRUSR | S_IRGRP, proc_dir,
				&alignment_proc_ops);
	} else {
		res = proc_create("cpu/alignment", S_IWUSR | S_IRUSR | S_IRGRP, NULL,
				&alignment_proc_ops);
	}

	if (!res)
		return -ENOMEM;
#endif

	return 0;
}

fs_initcall(alignment_init);
